package com.tcpengine.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

// websocket 处理
public class WsHandler extends ChannelInboundHandlerAdapter {
	private GameProcess gameProcess = null;
	public WsHandler(GameProcess gameProcess) {
		this.gameProcess = gameProcess;
	}
	
	
	@Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("有客户端连接:" + ctx.channel().remoteAddress());
    }
	@Override
	public void channelInactive(ChannelHandlerContext ctx)throws Exception{ 
    	System.out.println(ctx.channel().remoteAddress() + "关闭连接.........");
    	
	}
    @Override  
    public void channelRead(ChannelHandlerContext ctx, Object obj) {
		System.out.println("websocket 网络数据到达....");

		if (null != obj && obj instanceof BinaryWebSocketFrame) {
			System.out.println("收到二进制数据");
			ByteBuf byteBuf = ((BinaryWebSocketFrame)obj).content();
			Msg msg = Encoder.decode(byteBuf);
			if (null != msg) {
				NetPackage netPack = new NetPackage();
				netPack.ch = ctx.channel();
				netPack.msg = msg;
				netPack.netType = NetPackage.WS_TYPE;
				gameProcess.addPack(netPack);
			}
		}
		
    }  
   
    @Override  
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {	
        cause.printStackTrace();  
        ctx.close();  
    }
}
